// pages/vipCard/vipCard.js
const app = getApp();
const util = require('../../utils/util.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    baseImgUrl: app.globalData.apiImgUrl,
    cardStatus: 0, //0 未登录    1普通卡   2黑金卡
    interestList: [], //享受的权益
    title: '车主卡', //页面标题
    cardNumber: '', //卡号
    RelaId: '', //卡关联ID
    savingMoney: 6988, //节省金额
    exampleObj: {
      exampleImg: '', //示例图片
      exampleText: '', //描述
      exampleBtnText: '确定', //按钮文字
      exampleBtnUrl: '', //按钮路径
      exampleCardType: '', //1 不跳转   2 H5    3 小程序
      exampleLocationFlag: -1, //是否需要定位  1 需要  其他不需要
    },
    isHiddenExample: true, //是否隐藏示例
    cardVali: '', //会员卡有效期时间
    latitude: 0,
    longitude: 0,
    h5Url: '', //h5页面路径
  },
  // methods: {
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let self = this;
    self.getCardContent();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let self = this;
    app.globalData.isCurCarGroupList = false; //重置
    app.getSession().then(function () {
      let titleArr = ['车主卡', '普通卡', '黑金卡'];
      self.setData({
        cardStatus: app.globalData.userInfo.CardLevel,
        title: titleArr[app.globalData.userInfo.CardLevel]
      })
      if (self.data.cardNumber) {} else {
        self.getCardNumber();
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return app.globalData.shareInfo;
  },
  /**
   * 拨打电话
   */
  makeCallTap: function () {
    wx.makePhoneCall({
      phoneNumber: '4008756066'
    })
  },
  /**
   * 前往车去页面
   */
  loginTap: function () {
    let self = this;
    if (app.globalData.userInfo.UserID < 1) { //没有登录
      wx.navigateTo({
        url: '/pages/index/index',
      })
    } else {
      if (app.globalData.userInfo.VehicleStatus < 1) { //没有绑定车辆
        wx.navigateTo({
          url: '/pages/ucenter/drvlicense/drvlicense',
        })
      }
    }
  },
  /**
   * 升级为黑金卡
   */
  goToUpBlackCardTap: function () {
    let self = this;
    wx.navigateTo({
      url: '/pages/vipCard/updateBlackCard/updateBlackCard?RelaId=' + self.data.RelaId,
    })
  },
  /**
   * 获取卡片内容
   */
  getCardContent: function () {
    let self = this;
    let url = app.globalData.apiRootUrl + '/UserCard/GetCardContents';
    app.httpRequest({
      url: url,
      data: {
        level: 2
      },
      success: function (res) {
        console.log(res);
        let rdata = res.data;
        if (rdata.status == 0 && rdata.data.Contents.length > 0) {
          let tempList = rdata.data.Contents;
          let tempArr = [];
          for (let i = 0; i < tempList.length; i++) {
            tempArr = tempList[i].Description.split(' ');
            tempList[i].upTitle = tempArr[0];
            tempList[i].downTitle = tempArr[1];;
          }

          self.setData({
            interestList: tempList
          })
        }
      },
      fail: function (err) {

      }
    })
  },
  /**
   * 获取卡号
   */
  getCardNumber: function () {
    let self = this;
    let url = app.globalData.apiRootUrl + '/UserCard/GetUserCardList';
    app.httpRequest({
      url: url,
      data: {
        userId: app.globalData.userInfo.UserID
      },
      success: function (res) {
        let rdata = res.data;
        if (rdata.status == 0 && rdata.data.length > 0) {
          let now = util.formatDate(new Date(), 'yyyy-MM-dd'); //现在时间
          let creatDate = util.formatDate(rdata.data[0].UpdatedDate, 'yyyy-MM-dd'); //领卡时间
          let fullYearDayCount = util.getFullYearDayCount(now); //今年有多少天
          let dayCount = fullYearDayCount - util.countDateRange(creatDate, now); //会员卡还剩多少天
          self.setData({
            cardNumber: rdata.data[0].CardCode,
            RelaId: rdata.data[0].RelaId,
            cardVali: dayCount
          })
        }
      },
      fail: function (err) {

      }
    })
  },
  /**
   * 弹窗示例
   */
  showExampleTap: function (e) {
    let self = this;
    let id = e.currentTarget.dataset.serverid;
    let temp = {};
    if (id) {
      let interestList = self.data.interestList;
      for (let i = 0; i < interestList.length; i++) {
        if (interestList[i].CardContentId == id) {
          temp.exampleImg = interestList[i].DetailUrl;
          temp.exampleText = interestList[i].Description;
          temp.exampleBtnText = interestList[i].UrlName || '确定';
          temp.exampleBtnUrl = interestList[i].Url;
          temp.exampleCardType = interestList[i].CardType;
          temp.exampleLocationFlag = interestList[i].Category;
          //如果支付了，则显示支付的按钮和地址
          if (app.globalData.userInfo.CardLevel > 1) {
            temp.exampleBtnText = interestList[i].PayUrlName || '确定';
            temp.exampleBtnUrl = interestList[i].PayUrl;
          }
        }
      }
    } else {
      temp.exampleImg = self.data.baseImgUrl + 'common/mid-banner.jpg';
      temp.exampleText = '覆盖北京10w名德系车主，根据车友需求可深度链接资源';
      temp.exampleBtnText = '确定';
      temp.exampleBtnUrl = '';
      temp.exampleCardType = 1;
      temp.exampleLocationFlag = -1;
    }

    self.setData({
      exampleObj: temp,
      isHiddenExample: false
    })
  },
  /**
   * 跳转到其他小程序
   */
  goToWxMiniTap: function (e) {
    let self = this;
    let url = e.currentTarget.dataset.url; //路径地址
    let cardType = e.currentTarget.dataset.cardtype; //卡片类型
    let category = e.currentTarget.dataset.locationflag; // 是否需要定位

    self.setData({
      isHiddenExample: true
    })
    switch (cardType) {
      case 1: //不跳转

        break;
      case 2: //跳转H5
        if (category == 1) { //需要定位
          if (url) {
            self.setData({
              h5Url: url
            });
            self.checkLocation();
          } else {
            wx.showToast({
              title: '跳转失败，路径为空',
              icon: 'none'
            })
          }
        } else { //不需要定位
          if (url) {
            let query = '?webUrl=' + encodeURIComponent(url);
            wx.navigateTo({
              url: '/pages/webView/webView' + query,
            });
          }
        }
        break;
      case 3: //跳转小程序
        if (url) {
          wx.navigateToMiniProgram({
            appId: 'wx1f1ea04b716771be',
            path: url,
            extraData: {},
            envVersion: 'release',
            success(res) {
              //  console.log('')
            }
          });
        }
        break;
      case 4: //拨打电话
        if (url) {
          wx.makePhoneCall({
            phoneNumber: url
          })
        }
        break;
    }
  },
  /**
   * 检测定位权限
   */
  checkLocation: function () {
    let self = this;
    util.checkSetting("scope.userLocation").then(function (res) {
      self.getLocation();
    }).catch(function (res) {
      //没有权限，则开启设置页面
      util.openSetting("scope.userLocation", "定位洗车店需要获取定位权限,前往设置页面开启权限?").then(function (rt) {
        self.getLocation();
      }).catch(function (rt) {
        console.log('取消');
        let url = self.data.h5Url;
        let resUrl = url + '?latitude=' + self.data.latitude + '&longitude=' + self.data.longitude + '&userid=' + app.globalData.userInfo.UserID;
        let query = '?webUrl=' + encodeURIComponent(resUrl);
        wx.navigateTo({
          url: '/pages/webView/webView' + query,
        });
      });
    });

  },
  /**
   * 获取定位
   */
  getLocation: function () {
    let self = this;
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        const latitude = res.latitude
        const longitude = res.longitude
        self.setData({
          latitude: latitude,
          longitude: longitude
        })
      },
      fail(err) {
        self.setData({
          latitude: 0,
          longitude: 0
        })
      }
    })
    let url = self.data.h5Url;
    let resUrl = url + '?latitude=' + self.data.latitude + '&longitude=' + self.data.longitude + '&userid=' + app.globalData.userInfo.UserID;
    let query = '?webUrl=' + encodeURIComponent(resUrl);
    wx.navigateTo({
      url: '/pages/webView/webView' + query,
    });
  },
  /**
   * 关闭弹窗示例
   */
  closeExampleTap: function () {
    let self = this;
    self.setData({
      isHiddenExample: true
    })
  }
})